import { forwardRef, useEffect, useImperativeHandle } from "react";
import { Form, message } from "antd";
import moment from "moment";

import { IForm } from "@/components";
import { regExpMap } from "@/utils/consts";

import type { RecordItem } from "../type";
import type { FormItemConfig } from "@/components/FormItem";
import request from "@/utils/request";

interface Props {
	selRecord?: RecordItem;
}

const InfoForm = forwardRef((props: Props, ref) => {
	const [form] = Form.useForm();

	useEffect(() => {
		if (props.selRecord) {
			queryUserDetail();
		}
	}, [props.selRecord]);

	useImperativeHandle(ref, () => ({
		validateFields: () => {
			return form
				.validateFields()
				.then(value => {
					return {
						...value
						// accountExpire: formatDateShowTime(value.accountExpire),
					};
				})
				.catch((error: any) => {
					message.warn("请完善用户基本信息");
					throw error;
				});
		}
	}));

	const queryUserDetail = () => {
		// 管理员详情接口
		request("userManageQueryById",
			{ data: { userId: props.selRecord?.id } })
			.then(res => {
				if (res.code === 0 && res.data) {
					const { accountExpire } = res.data;
					form.setFieldsValue({
						...res.data
						// accountExpire: momentDate(accountExpire)
					});
				}
			});
	};

	const formItemsConfig: FormItemConfig[] = [
		{
			type: "input",
			formItemProps: {
				label: "用户名",
				name: "username"
				// rules: [{ required: true }]
			}
		},
		{
			type: "input",
			formItemProps: {
				label: "手机号",
				name: "mobile",
				rules: [{ required: true }, { pattern: regExpMap.mobile, message: "请输入正确手机号" }]
			}
		},
		{
			type: "input",
			formItemProps: {
				label: "姓名",
				name: "realName",
				rules: [{ required: true }]
			}
		},
		!props.selRecord
			? {
				type: "inputPassword",
				formItemProps: {
					label: "登录密码",
					name: "password",
					rules: [
						{ required: true }
						// {
						// 	pattern: regExpMap.userPassword,
						// 	message: "8-16个字符，需包含大小写字母、数字及特殊字符"
						// }
					]
				},
				childProps: {
					prefix: null,
					placeholder: "请输入密码"
				}
			}
			: null,
		!props.selRecord
			? {
				type: "inputPassword",
				formItemProps: {
					label: "确认密码",
					name: "confirmPassword",
					dependencies: ["password"],
					rules: [{ required: true }]
				},
				childProps: {
					prefix: null,
					placeholder: "请输入确认密码"
				}
			}
			: null
	];

	return <IForm layout="vertical" form={form} formItemsConfig={formItemsConfig}></IForm>;
});

InfoForm.displayName = "InfoForm";

export default InfoForm;
